package com.lazypeople.controller;

import com.lazypeople.util.ConfigUtils;
import com.lazypeople.domain.DownloadSetting; // 新增导入

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextField;
import javafx.scene.control.SpinnerValueFactory;
import javafx.stage.DirectoryChooser;
import java.io.File;
import javafx.stage.Stage;
import javafx.scene.control.Alert; // 需要添加该导入语句才能解决 Alert 无法解析的问题

public class SettingsController {
    @FXML
    private TextField defaultDirField; // Renamed from savePathField
    @FXML
    private Spinner<Integer> threadCountSpinner;
    @FXML
    private Spinner<Integer> maxConcurrentSpinner; // Renamed from threadCountSpinner
    @FXML // 新增
    private Spinner<Integer> maxTaskSpinner;
    // 为解决 browseButton 无法解析的问题，需要先添加 @FXML 注解声明该字段
    @FXML
    private Button browseButton;
    // 为解决 saveButton 无法解析的问题，需要先添加 @FXML 注解声明该字段
    @FXML
    private Button saveButton;

    @FXML
    private Button cancelButton;

    public void initialize() {
        // 从Util类加载配置对象
        DownloadSetting setting = ConfigUtils.loadDownloadSetting();
        
        // 从对象读取配置并设置UI
        defaultDirField.setText(setting.getDefaultSavePath());
        maxConcurrentSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 10,
                setting.getThreadCount()));
        maxTaskSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 20,
                setting.getMaxTaskCount()));

        browseButton.setOnAction(e -> chooseSavePath());
        saveButton.setOnAction(e -> saveSettings());
        cancelButton.setOnAction(e -> cancelSettings());
    }

    // 重构：使用对象保存配置
    private void saveSettings() {
        DownloadSetting setting = new DownloadSetting();
        setting.setDefaultSavePath(defaultDirField.getText());
        setting.setThreadCount(maxConcurrentSpinner.getValue());
        setting.setMaxTaskCount(maxTaskSpinner.getValue());
        // 如需保存其他配置项（theme/language等），可在此处添加

        // 保存整个对象到文件
        ConfigUtils.saveDownloadSetting(setting);

        new Alert(Alert.AlertType.INFORMATION, "配置已成功保存", javafx.scene.control.ButtonType.OK).showAndWait();
    }

    private void chooseSavePath() {
        DirectoryChooser chooser = new DirectoryChooser();
        File dir = chooser.showDialog(defaultDirField.getScene().getWindow());
        if (dir != null) {
            defaultDirField.setText(dir.getAbsolutePath());
        }
    }

    private void cancelSettings() {
        // 获取当前窗口并关闭
        Stage stage = (Stage) defaultDirField.getScene().getWindow();
        stage.close();
    }
}